<?php


namespace app\api;


use app\BaseController;
use app\service\TokenService;
use think\App;

/**
 * API 项目的基类
 * Class BaseApi
 * @package app\api
 */
class BaseApi extends BaseController
{
    /**
     * 缓存KEY
     */
    const TOKEN_KEY = 'access_token';
    const CACHE_KEY = "TOKEN_";
    const ERROR_CODE = '100103';
    /**
     * 可以不用检验登录信息的url
     * @var array
     */
    protected static $ignoreUrl = [
        'api/token/getAccessToken',
    ];

    public function __construct()
    {
        $this -> auth();
    }

    /**
     * 权限校验
     * @throws BusinessException
     */
    private function auth()
    {
        //白名单 && THINK_ENV != CODE_RUNTIME_LOCAL
        if (!in_array(Request()->pathinfo(), self::$ignoreUrl)) {
            //签名
            $token = input(self::TOKEN_KEY);
            if (empty($token)) {
//                Log::record("authFailure_params:".json_encode(input()));
                $result =[
                    'status' =>0,
                    'code' => '2000011',
                    'data' => '',
                    'msg'=> 'no have access_token'
                ];
                echo json_encode($result);
                die();
            }
            //跑脚本代码专用
            if ($token == 'dx123') {
                return;
            }
            //检测服务器状态专用
            if ($token == 'a2f72346e68978755153e4a2d0fb2d4c') {
                return;
            }
            $tokenService = new TokenService();
            $where = [
                        ['app_token', '=', $token],
                        ['expiration_time', '>', time() ],
                     ];
            //检查token 是否过期
            $result = $tokenService ->checkToken($where);
            if(empty($result)){
                $result =[
                    'status' =>0,
                    'code' => '2000012',
                    'data' => '',
                    'msg'=> 'The Token is expired !'
                ];
                echo json_encode($result);
                die();
            }else{
                //dump($result);
            }
//            $token = input(self::TOKEN_KEY);
//            if(empty($token)){
//                echo (json_encode(['code'=>2000010, 'msg'=>'no have access_token']));die;
//            }
//            $auth = (new RedisClusterBase())->get(self::CACHE_KEY . $token);
//            if (!$auth) {
//                echo (json_encode(['code'=>2000011, 'msg'=>'The Token is expired !']));die;
//            }
        }
    }


    /**
     * 验证输入的手机号码--先写入基类吧
     * @access public
     * @param string $user_mobile 需要验证的手机号码
     * @return bool
     * @return bool
     */
    public function isMobile(string $user_mobile): bool
    {
        $chars = "/^((\(\d{2,3}\))|(\d{3}\-))?1(3|5|8|9)\d{9}$/";
        if (preg_match($chars, $user_mobile)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取文件名称--随机唯一名称
     */
    public function getFileName() : string {
        //生成随机文件名
        $hash="CR-";
        //定义一个包含大小写字母数字的字符串
        $chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        //把字符串分割成数组
        $newchars=str_split($chars);
        //打乱数组
        shuffle($newchars);
        //从数组中随机取出15个字符
        $chars_key=array_rand($newchars,15);
        $fnstr='';
        //把取出的字符重新组成字符串
        for($i=0;$i<15;$i++){
            $fnstr.=$newchars[$chars_key[$i]];
        }
        $str_m = $fnstr.time()*1000000;
        //$str_m = $fnstr.time().microtime()*1000000;
        //var_dump($str_m);die();
        //输出文件名并做MD5加密
        $result = $hash.md5($str_m);
        return $result;
    }

    /**
     * 获取某个VIP等级用户每天可以做的任务数据
     * @param int $lv
     * @return int
     */
    public function getVipTaskCount(int $lv): int{
        $result = 3;
        switch ($lv){
            case 1:
                $result = 9;
                break;
            case 2:
                $result = 26;
                break;
            case 3:
                $result = 65;
                break;
            case 4:
                $result = 60;
                break;
            case 5:
                $result = 90;
                break;
            case 6:
                $result = 75;
                break;
            case 7:
                $result = 110;
                break;
            default:
                $result = 3; //0级用户默认给三个任务
                break;
        }
        return $result;
    }


}